package manager;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import utils.DBConnector;

/**
 * Servlet implementation class AddCourseToDB
 */
public class AddCourseToDB extends BaseCMServlet {
	private static final long serialVersionUID = 1L;
	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		if (request.getSession(false) == null || request.getSession(false).getAttribute("username") == null){
			response.sendError(HttpServletResponse.SC_FORBIDDEN, "Please login first");
			return;
		}
		
		if (!request.getSession(false).getAttribute("type").equals("admin")) {
			response.sendError(HttpServletResponse.SC_FORBIDDEN, "Only Admin can add courses");
			return;			
		}
		
		String name = request.getParameter("course_name");
		String desription = request.getParameter("course_desription");
		int credit = Integer.parseInt(request.getParameter("course_credit"));
		int capacity = Integer.parseInt(request.getParameter("course_capacity"));
		int group = Integer.parseInt(request.getParameter("course_group"));
		
		// TODO: more checking here 
		if (name         == null || 
			desription   == null ||
			credit       <= 0 ||
			capacity     <= 0 ||
			group        <= 0)
		{
			    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "some missing/wrong parameter");
				return;
						
		}
		
		DBConnector dbConn = null;
		try {
			dbConn = new DBConnector();
			PreparedStatement stmnt = dbConn.getConnection().prepareStatement(
					"INSERT INTO courses (course_name, description, credit_points, capacity, group_number, is_active) " +
					"VALUES(?,?,?,?,?,FALSE)");
			
			int i = 1;
			stmnt.setString(i++, name);
			stmnt.setString(i++, desription);
			stmnt.setInt(i++, credit);
			stmnt.setInt(i++, capacity);
			stmnt.setInt(i++, group);			
			stmnt.executeUpdate();		
			
			
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The course " + name + " Already exist in the system");
			return;
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			try {
				dbConn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		response.sendRedirect("manage_courses.jsp");		
	}
	
}
